package com.financing.wap.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;


@SuppressWarnings(value={"all"})
public class SecureUtil {
	private final static String SALT = "fa123";
	private final static String JOBSALT = "sfa1qa2ws";
	static Logger log = Logger.getLogger(SecureUtil.class);
	
    //十六进制下数字到字符的映射数组  
    private final static String[] hexDigits = {"0", "1", "2", "3", "4",  
        "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};  
	
	public static String MD5EncryptAndBase64(String str){
		
		if(StringUtils.isEmpty(str)){
			return null;
		}
		
		//添加干预字段
		str = str + SALT; 
		
		MessageDigest md = null;
		BASE64Encoder baseEncoder = new BASE64Encoder();
		
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			log.error("MD5 Encrypt error",e);
			return null;
		}
		
		return baseEncoder.encode(md.digest(str.getBytes()));
	}
	public static String MD5EncryptAndBase64ForJOB(String str,String salt){
		
		if(StringUtils.isEmpty(str)){
			return null;
		}
		
		//添加干预字段
		str = str + salt; 
		
		try{  
            //创建具有指定算法名称的信息摘要  
            MessageDigest md = MessageDigest.getInstance("MD5");  
            //使用指定的字节数组对摘要进行最后更新，然后完成摘要计算  
            byte[] results = md.digest(str.getBytes());  
            //将得到的字节数组变成字符串返回  
            String resultString = byteArrayToHexString(results);  
            
            return resultString;
            
        } catch(Exception e){  
        	log.error("MD5 Encrypt error",e);
            return null;
        }  
		
	}
	public static String MD5EncryptAndBase64Sign(String actCode,String t){
        
		return MD5EncryptAndBase64ForJOB(actCode+t,JOBSALT);
		
	}
	/**  
     * 转换字节数组为十六进制字符串 
     * @param     字节数组 
     * @return    十六进制字符串 
     */  
    private static String byteArrayToHexString(byte[] b){  
        StringBuffer resultSb = new StringBuffer();  
        for (int i = 0; i < b.length; i++){  
            resultSb.append(byteToHexString(b[i]));  
        }  
        return resultSb.toString();  
    }  
      
    /** 将一个字节转化成十六进制形式的字符串     */  
    private static String byteToHexString(byte b){  
        int n = b;  
        if (n < 0)  
            n = 256 + n;  
        int d1 = n / 16;  
        int d2 = n % 16;  
        return hexDigits[d1] + hexDigits[d2];  
    }  

    // 加密
    public static String encrypt(String sSrc) throws Exception {
    	 String sKey="fas!@#@fdas23FDA";
    	 String ivParameter="98fda823<>?@#s13";
	    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	    byte[] raw = sKey.getBytes();
	    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
	    IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度
	    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
	    byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
	    return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
    }
    
    // 解密
    public static String decrypt(String sSrc) throws Exception {
    	String sKey="fas!@#@fdas23FDA";
   	 	String ivParameter="98fda823<>?@#s13";
	    try {
		    byte[] raw = sKey.getBytes("ASCII");
		    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		    IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
		    cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
		    byte[] encrypted1 =  new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
		    byte[] original = cipher.doFinal(encrypted1);
		    String originalString = new String(original,"utf-8");
		    return originalString;
	    } catch (Exception ex) {
	    	ex.printStackTrace();
	    	return null;
	    }
	  }
    
    public static String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
//            System.out.println("MD5(" + sourceStr + ",32) = " + result);
//            System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));
            return result;
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
//		String token = "/v2ApErWk1k+vaCRd462OOSyBmdpSGLhCAA7JoMmvdE=";
//		token = decrypt(token);
//		System.out.println(token);
    	System.out.println(encrypt("303"));
    	
	}
    
}